import { makeObservable, observable, action, runInAction } from "mobx";
import axios from "axios";

export interface User {
  id: number;
  first_name: string;
  last_name: string;
  email: string;
  avatar: string;
}

class MessageStore {
  users: User[] = [];
  page = 1;
  isLoading = false;
  isRefreshing = false;
  hasMore = true;

  constructor() {
    makeObservable(this, {
      users: observable,
      isRefreshing: observable,
      isLoading: observable,
      hasMore: observable,
      fetchUsers: action,
      onRefresh: action,
      onLoadMore: action,
      loadData: action,
    });
  }

  fetchUsers = async (pageNum: number) => {
    try {
      const response = await axios.get(
        `https://reqres.in/api/users?page=${pageNum}`
      );
      const { data, page, total_pages } = response.data;
      runInAction(() => {
        this.users = pageNum === 1 ? data : [...this.users, ...data];
        this.hasMore = page < total_pages;
      });
    } catch (error) {
      console.error("Failed to fetch users:", error);
    } finally {
      runInAction(() => {
        this.isLoading = false;
        this.isRefreshing = false;
      });
    }
  };

  loadData = () => {
    this.fetchUsers(this.page);
  };

  onRefresh = () => {
    if (this.isRefreshing || this.isLoading) return;
    this.isRefreshing = true;
    this.page = 1;
    this.fetchUsers(this.page);
  };

  onLoadMore = () => {
    if (!this.isRefreshing && !this.isLoading && this.hasMore) {
      this.isLoading = true;
      this.page += 1;
      this.fetchUsers(this.page);
    }
  };
}

const messageStore = new MessageStore();

export default messageStore;
